'use strict';
const db = uniCloud.database();
const dbCmd = db.command;

/**
 * 每日订单同步定时任务
 * 每天0点执行，拉取前一天的所有订单，确保数据完整性
 */
exports.main = async (event, context) => {
    console.log('开始执行每日订单同步定时任务...');
    const now = new Date();
    
    // 计算前一天的时间范围（0点到23:59:59）
    const yesterday = new Date(now);
    yesterday.setDate(yesterday.getDate() - 1);
    yesterday.setHours(0, 0, 0, 0);
    
    const yesterdayEnd = new Date(yesterday);
    yesterdayEnd.setHours(23, 59, 59, 999);
    
    const startTime = Math.floor(yesterday.getTime() / 1000);
    const endTime = Math.floor(yesterdayEnd.getTime() / 1000);
    
    console.log(`同步时间范围: ${yesterday.toISOString()} 至 ${yesterdayEnd.toISOString()}`);
    console.log(`时间戳范围: ${startTime} 至 ${endTime}`);
    
    // 获取access_token
    let accessToken;
    try {
        const tokenRes = await uniCloud.callFunction({
            name: 'wx-api-center',
            data: { action: 'getAccessToken' }
        });
        if (tokenRes.result.code !== 0) {
            throw new Error(tokenRes.result.message);
        }
        accessToken = tokenRes.result.accessToken;
        console.log('✅ access_token获取成功');
    } catch (err) {
        console.error('❌ 获取access_token失败:', err.message);
        return { error: '获取access_token失败', message: err.message };
    }
    
    // 调用微信API获取订单列表
    const listUrl = `https://api.weixin.qq.com/channels/ec/order/list/get?access_token=${accessToken}`;
    const requestData = {
        create_time_range: {
            start_time: startTime,
            end_time: endTime
        },
        page_size: 100
    };
    
    let allOrders = [];
    let hasMore = true;
    let nextKey = '';
    
    // 分页获取所有订单
    while (hasMore) {
        try {
            if (nextKey) {
                requestData.next_key = nextKey;
            }
            
            const listRes = await uniCloud.httpclient.request(listUrl, {
                method: 'POST',
                contentType: 'json',
                dataType: 'json',
                data: requestData
            });
            
            if (!listRes.data || listRes.data.errcode !== 0) {
                console.error('❌ 获取订单列表失败:', listRes.data?.errmsg);
                break;
            }
            
            const orders = listRes.data.order_id_list || [];
            allOrders = allOrders.concat(orders);
            
            hasMore = listRes.data.has_more || false;
            nextKey = listRes.data.next_key || '';
            
            console.log(`获取到 ${orders.length} 条订单，总计 ${allOrders.length} 条`);
            
        } catch (err) {
            console.error('❌ 获取订单列表失败:', err.message);
            break;
        }
    }
    
    if (allOrders.length === 0) {
        console.log('前一天没有订单。任务结束。');
        return { totalOrders: 0, syncedCount: 0, updatedCount: 0, skippedCount: 0 };
    }
    
    console.log(`前一天共有 ${allOrders.length} 条订单，开始同步...`);
    
    let syncedCount = 0; // 新创建的订单
    let updatedCount = 0; // 更新的订单
    let skippedCount = 0; // 跳过的订单
    let errorCount = 0; // 错误的订单
    
    // 获取分销规则
    const settingsRes = await db.collection('settings').doc('rules').get();
    const rules = settingsRes.data.length > 0 ? settingsRes.data[0] : {};
    
    for (const orderId of allOrders) {
        try {
            // 检查订单是否已存在
            const existCheck = await db.collection('orders').doc(orderId).get();
            const existingOrder = existCheck.data.length > 0 ? existCheck.data[0] : null;
            
            // 获取订单详情
            const detailUrl = `https://api.weixin.qq.com/channels/ec/order/get?access_token=${accessToken}`;
            const detailRes = await uniCloud.httpclient.request(detailUrl, {
                method: 'POST',
                contentType: 'json',
                dataType: 'json',
                data: { order_id: orderId }
            });
            
            if (!detailRes.data || detailRes.data.errcode !== 0) {
                console.error(`❌ 获取订单 ${orderId} 详情失败:`, detailRes.data?.errmsg);
                errorCount++;
                continue;
            }
            
            const order = detailRes.data.order;
            const openid = order.openid;
            const unionid = order.unionid;
            
            // 查找用户
            let userQuery = { data: [] };
            const wechatStoreAppId = 'wx64874b77c972fb53';
            
            if (unionid) {
                userQuery = await db.collection('users').where({ wx_unionid: unionid }).limit(1).get();
            }
            
            if (userQuery.data.length === 0 && openid) {
                const queryCondition = {};
                queryCondition[`wx_openid.${wechatStoreAppId}`] = openid;
                userQuery = await db.collection('users').where(queryCondition).limit(1).get();
            }
            
            if (userQuery.data.length === 0) {
                console.log(`⚠️ 订单 ${orderId} 的购买用户未找到，跳过`);
                skippedCount++;
                continue;
            }
            
            const buyerInfo = userQuery.data[0];
            const buyerUid = buyerInfo._id;
            const promoterId = buyerInfo.promoter_id;
            
            // 映射订单状态
            const wechatStatus = order.status;
            let ourStatus = 'paid';
            let completedTime = null;
            
            if (wechatStatus === 100) {
                ourStatus = 'completed';
                completedTime = Date.now();
            } else if (wechatStatus === 200) {
                ourStatus = 'cancelled';
            } else if (wechatStatus === 250) {
                ourStatus = 'refunded';
            } else if (wechatStatus === 30) {
                ourStatus = 'shipped';
            } else if (wechatStatus === 20) {
                ourStatus = 'paid';
            } else if (wechatStatus === 10) {
                ourStatus = 'unpaid';
            }
            
            // 计算佣金
            const orderAmount = order.order_detail.price_info.order_price;
            const commissionRate = rules.commission?.purchaseRebate || 0.1;
            const commissionAmount = promoterId ? Math.round(orderAmount * commissionRate) : 0;
            
            if (!existingOrder) {
                // 创建新订单
                const orderData = {
                    _id: orderId,
                    buyer_id: buyerUid,
                    promoter_id: promoterId || null,
                    amount: orderAmount,
                    status: ourStatus,
                    create_time: order.create_time * 1000,
                    completed_time: completedTime,
                    product_details: order.order_detail.product_infos.map(p => ({
                        name: p.title,
                        quantity: p.count,
                        price: p.sale_price
                    })),
                    commission_amount: commissionAmount,
                    commission_status: promoterId && ourStatus === 'paid' ? 'pending' : null,
                    points_awarded: 0,
                    buyer_points_awarded: 0,
                    source: 'wechat_store',
                    last_sync_time: Date.now(),
                    // ✅ 修复：统一激活周期为 7 天
                    activation_countdown: 7,
                    activation_date: completedTime ? completedTime + 7 * 24 * 60 * 60 * 1000 : null
                };
                
                await db.collection('orders').add(orderData);
                syncedCount++;
                console.log(`✅ 新订单 ${orderId} 已创建`);
                
            } else if (existingOrder.status !== ourStatus) {
                // 更新订单状态
                const updateData = {
                    status: ourStatus,
                    last_sync_time: Date.now()
                };
                
                if (ourStatus === 'completed' && !existingOrder.completed_time) {
                    updateData.completed_time = Date.now();
                    // ✅ 修复：统一激活周期为 7 天
                    updateData.activation_date = Date.now() + 7 * 24 * 60 * 60 * 1000;
                    updateData.activation_countdown = 7;
                }
                
                await db.collection('orders').doc(orderId).update(updateData);
                updatedCount++;
                console.log(`✅ 订单 ${orderId} 状态已更新: ${existingOrder.status} → ${ourStatus}`);
                
            } else {
                skippedCount++;
            }
            
        } catch (err) {
            console.error(`❌ 处理订单 ${orderId} 失败:`, err.message);
            errorCount++;
        }
    }
    
    console.log(`任务完成。总订单数: ${allOrders.length}, 新创建: ${syncedCount}, 更新: ${updatedCount}, 跳过: ${skippedCount}, 错误: ${errorCount}`);
    return {
        totalOrders: allOrders.length,
        syncedCount,
        updatedCount,
        skippedCount,
        errorCount,
        message: `同步完成，总订单数: ${allOrders.length}, 新创建: ${syncedCount}, 更新: ${updatedCount}`
    };
};

